import {useRoute} from 'vue-router'
import qs from 'qs'
import {EmptyUtil} from "@/utils";


export class MenuUtil {
    static getActiveMenu() {
        const route = useRoute()
        return !route.path ? '' : route.path
    }

    /**
     * 根据当前route获取激活菜单
     * @param route 当前路由
     * @param checkParams 是否需要区分不同的请求参数
     * @returns {string|*}
     */
    static handleActivePath(route, checkParams = false) {
        const {meta, path} = route

        const rawPath = route.matched ? route.matched[route.matched.length - 1].path : path
        const fullPath = route.query && Object.keys(route.query).length ? `${route.path}?${qs.stringify(route.query)}` : route.path
        if (checkParams) {
            return meta.dynamicNewTab ? fullPath : rawPath
        }
        return fullPath
    }

    /**
     * 将路由转换成标签存储对象 需要区分不同的参数新建不同的选项卡
     */
    static routeCoverToTabData(route): any {
        const path = this.handleActivePath(route, true)
        if (route.name)
            return {
                path,
                query: 'query' in route ? route.query : {},
                params: 'params' in route ? route.params : {},
                name: route.name as string,
                meta: {...route.meta},
            }
        return null
    }


    // 图标加载
    static renderIcon = (iconName: string) => {
        if (EmptyUtil.isEmptyString(iconName)) return ''
        return <smart-icon name={iconName} size={18}/>
    }


    /**
     * 最子集路由数据格式化
     * */
    static createMenuItem = menuRoute => {
        return (
            <a-menu-item key={menuRoute.path}>
                {menuRoute.meta.title}
                <span class="expand">
            {menuRoute.meta.badge ? (
                <t-tag size="small" variant="light" theme="danger">
                    {menuRoute.meta.badge}
                </t-tag>
            ) : (
                ''
            )}
        </span>
            </a-menu-item>
        )
    }

    /**
     * 存在子路由时进行的数据解析
     * */
    static createSubMenuItem(item) {
        return item.meta.groupMode ? (
            <a-menu-item-group key={item.path} v-slots={{title: () => item.meta.title}}>
                {this.useRenderNav(item.children)}
            </a-menu-item-group>
        ) : (
            <a-sub-menu key={item.path} title={item.meta.title}
                        v-slots={{
                            icon:()=>  this.renderIcon(item.meta.icon)
                        }}>


                {this.useRenderNav(item.children)}
            </a-sub-menu>
        )
    }


    // 构建目录结构
    static useRenderNav(list) {
        return list.map(item => {
            if (EmptyUtil.isEmptyArray(item.children)) {
                return this.createMenuItem(item)
            }
            // 存在子菜单的情况构造
            return this.createSubMenuItem(item)
        })
    }

}
